<template>
  <el-dialog
      v-model="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
  >
    <div class="auth-container">
      <h2 class="dialog-title">{{ isLogin ? '欢迎登录' : '用户注册' }}</h2>

      <transition :name="transitionName" mode="out-in">
        <el-form
            :key="isLogin ? 'login' : 'register'"
            :model="formData"
            :rules="formRules"
            ref="formRef"
            @submit.prevent="handleSubmit"
            class="auth-form"
        >
          <!-- 登录表单 -->
          <template v-if="isLogin">
            <el-form-item prop="username">
              <el-input
                  v-model="formData.userName"
                  placeholder="请输入用户名"
                  prefix-icon="User"
                  size="large"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="formData.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  size="large"
                  show-password
              />
            </el-form-item>
          </template>

          <!-- 注册表单 -->
          <template v-else>
            <el-form-item prop="username">
              <el-input
                  v-model="formData.userName"
                  placeholder="请输入用户名"
                  prefix-icon="User"
                  size="large"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="formData.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  size="large"
                  show-password
              />
            </el-form-item>
            <el-form-item prop="nickname">
              <el-input
                  v-model="formData.nickName"
                  placeholder="请输入昵称"
                  prefix-icon="Avatar"
                  size="large"
              />
            </el-form-item>
          </template>

          <el-button
              type="primary"
              size="large"
              native-type="submit"
              class="submit-btn"
              :loading="loading"
          >
            {{ isLogin ? '立即登录' : '立即注册' }}
          </el-button>
        </el-form>
      </transition>

      <div class="switch-action">
        <span class="tip-text">
          {{ isLogin ? '没有账号？' : '已有账号？' }}
        </span>
        <el-button
            link
            type="primary"
            @click="switchForm"
            class="switch-btn"
        >
          {{ isLogin ? '去注册' : '去登录' }}
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {login, register, setIp} from "@/api/login.js";
import axios from "axios";

const dialogVisible = ref(false)
const isLogin = ref(true)
const transitionName = ref('slide-left')
const loading = ref(false)
const formRef = ref(null)

const emit = defineEmits(['reload'])
const formData = reactive({
  userName: 'user',
  password: '123456',
  nickName: ''
})

const formRules = {
  userName: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 4, max: 16, message: '长度在4到16个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur'}
  ],
  nickName: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur'}
  ]
}

const switchForm = () => {
  transitionName.value = isLogin.value ? 'slide-left' : 'slide-right'
  isLogin.value = !isLogin.value
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    if (isLogin.value) {
      login(formData).then(res => {
        ElMessage({message: '登录成功', type: 'success'})
        localStorage.setItem("token", res.data.token)
        localStorage.setItem("healthUser", JSON.stringify(res.data.user))
        loading.value = false
        axios.get('https://qifu-api.baidubce.com/ip/local/geo/v1/district').then(res => {
          let kh = {
            ip: res.data.ip,
            province: res.data.data.prov,
            city: res.data.data.city,
            district: res.data.data.district
          }
          setIp(kh)
        }).catch(err => {
          let kh = {
            ip: '未知',
            province: '未知',
            city: '未知',
            district: '未知'
          }
          setIp(kh)
        })
        dialogVisible.value = false
        emit('reload')
      }).catch(err=>{
        loading.value = false
      })
    }else {
      register(formData).then(res => {
        ElMessage({
          message: '注册成功,正在自动登录',
          type: 'success',
        })
        isLogin.value = true
        handleSubmit()
      })
    }


  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 暴露打开弹窗方法
const open = () => {
  dialogVisible.value = true
}


defineExpose({open})
</script>

<style scoped>
.auth-container {
  padding: 24px;
}

.dialog-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 500;
}

.auth-form {
  min-height: 220px;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
  letter-spacing: 2px;
}

.switch-action {
  text-align: center;
  margin-top: 20px;
}

.tip-text {
  color: #666;
  font-size: 14px;
}

.switch-btn {
  padding: 0 4px;
  height: auto;
}

/* 切换动画 */
.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.3s ease;
}

.slide-left-enter-from {
  opacity: 0;
  transform: translateX(50px);
}

.slide-left-leave-to {
  opacity: 0;
  transform: translateX(-50px);
}

.slide-right-enter-from {
  opacity: 0;
  transform: translateX(-50px);
}

.slide-right-leave-to {
  opacity: 0;
  transform: translateX(50px);
}
</style>